package zhu.areas.match.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import zhu.areas.match.dao.IAttendListDAO;
import zhu.areas.match.data.AttendList;
import zhu.areas.match.data.CompApp;
import zhu.areas.match.data.MatchStatue;
import zhu.areas.match.data.MatchType;
import zhu.areas.match.data.Sponsor;
import zhu.areas.match.service.CompAppServiceImpl;
import zhu.areas.match.service.ICompAppService;
import zhu.areas.match.service.IMatchService;
import zhu.areas.user.data.User;
import zhu.common.data.PageBean;
import zhu.common.data.Pager;

import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

//大赛
public class MatchAction extends ActionSupport {

	private IMatchService matchService;
	private ICompAppService compAppService;
	private List<MatchType> matchTypeList;
	
	private int compId;
	private int userId;
	private String userName;
	private int compStatue;

	private CompApp compApp;
	private Sponsor sponsor;
	private AttendList attendList;

	private File uploadFile;
	private String uploadFileContentType;
	private String uploadFileFileName;
	private String targetFileName;
	private String downloadFileFileName;
	private String downloadFileContentType;
	private String downloadPath;
	private InputStream inputStream;

	public String compApp() throws IOException {
		this.clearErrorsAndMessages();
		System.out.println(compApp.getcMoney() + "---" + compApp.getCompName()
				+ "---" + compApp.getAppEndDate());
		compApp.setStatue(new MatchStatue(1)); // 设置为未通过状态
		compApp.setAppTime(new Date());
		Object uID = ServletActionContext.getRequest().getSession()
				.getAttribute("userID");
		if (uID == null){
			this.addActionMessage("请先登录!");
			return INPUT;
			}
		userId = Integer.parseInt(uID.toString());
		User applier = new User(userId);
		compApp.setApplier(applier);
		if (uploadFile != null) {
			uploadFile();
			compApp.setpAddress(targetFileName);// File(".","uploadFiles/"+uploadFileFileName).toString()
			compApp.setAttachmentName(uploadFileFileName); // getText("filePath.tenderFilePath")+"/"
		}
		compAppService.saveCompApp(compApp);
		return SUCCESS;
	}

	public String toCompApp() {
		this.clearErrorsAndMessages();
		Object uID = ServletActionContext.getRequest().getSession()
				.getAttribute("userID");
		if (uID == null){
			this.addActionMessage("请先登录!");
			return INPUT;
			}
		matchTypeList = matchService.findAllMatchTypes();
		return SUCCESS;
	}

	public String compAppSponsor() {
		this.clearErrorsAndMessages();
		Object uID = ServletActionContext.getRequest().getSession()
				.getAttribute("userID");
		if (uID == null){
			this.addActionMessage("请先登录!");
			return INPUT;
			}
		userId = Integer.parseInt(uID.toString());
		this.ConverToSponsor();
		matchService.saveSponsor(sponsor);
		this.addActionMessage("保存成功");
		return SUCCESS;
	}

	public String toSponsor() {
		this.clearErrorsAndMessages();
		Object uID = ServletActionContext.getRequest().getSession()
				.getAttribute("userID");
		if (uID == null){
			this.addActionMessage("请先登录!");
			return INPUT;
			}
		compApp = compAppService.findCompAppById(compId);
		return SUCCESS;
	}

	public String compApply() {
		this.clearErrorsAndMessages();
		if (matchService.checkAttendlist(userId, compId)) {
			addActionError("您已经报名！");
			return ERROR;
		}
		Object uID = ServletActionContext.getRequest().getSession()
				.getAttribute("userID");
		if (uID == null){
			this.addActionMessage("请先登录!");
			return INPUT;
			}
		userId = Integer.parseInt(uID.toString());
		this.convertToAttendList();
		System.out.println(attendList.getApplierName());
		matchService.saveAttendList(attendList);
		this.addActionMessage("保存成功");
		return SUCCESS;
	}

	public String ToCompApply() {
		this.clearErrorsAndMessages();
		Object uID = ServletActionContext.getRequest().getSession()
				.getAttribute("userID");
		if (uID == null){
			this.addActionMessage("请先登录!");
			return INPUT;
			}
		compApp = compAppService.findCompAppById(compId);
		return SUCCESS;
	}

	public String outDateComp() {
		compAppService.setCompOutDate(compId);
		return SUCCESS;
	}

	public void checkUserName() {
		String uname = ServletActionContext.getRequest().getSession()
				.getAttribute("userName").toString();
		try {
			if (uname.equals(this.userName)) {
				ServletActionContext.getResponse().getWriter().print("true");
			} else
				ServletActionContext.getResponse().getWriter().print("false");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 发布所有通过的申请表
	public String pubAllPassedComp() {
		int count = compAppService.pubAllPassedComp();
		System.out.println("共发布了" + count + "条申请!");
		return SUCCESS;
	}

	public String pubCompAppById() {
		compApp = compAppService.findCompAppById(compId);
		compApp.setStatue(new MatchStatue(5));
		compAppService.updateCompApp(compApp);
		return SUCCESS;
	}

	public String downloadFile() throws Exception {
		System.out.println(downloadFileFileName);
		downloadPath = getText("filePath.tenderFilePath") + "/"
				+ downloadFileFileName;
		System.out.println(downloadPath);
		int position = downloadPath.lastIndexOf("/");
		int extPos = downloadFileFileName.lastIndexOf(".");
		String contentTypeKey;
		if (extPos > 0) {
			contentTypeKey = "struts.contentType"
					+ downloadFileFileName.substring(extPos);
		} else {
			contentTypeKey = "struts.contentType.txt";
		}

		downloadFileContentType = getText(contentTypeKey);
		System.out.println("type:" + getText(contentTypeKey));
		return SUCCESS;
	}

	// 文件上传
	public void uploadFile() throws IOException {
		if (uploadFile != null) {
			System.out.println("uploadFileName:" + uploadFileFileName);
			String serverRealPath = getText("filePath.tenderFilePath"); // ServletActionContext.getServletContext().getRealPath("/UploadFiles");
			File dir = new File(serverRealPath);
			if (!dir.exists()) {
				dir.mkdir();
			}
			targetFileName = genNewFileName(uploadFileFileName);
			File targetFile = new File(serverRealPath, targetFileName);
			FileUtils.copyFile(uploadFile, targetFile);
			addActionMessage("文件上传成功！");
		}

	}

	private String genNewFileName(String fileName) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String newFileName = sf.format(Calendar.getInstance().getTime());
		int beginIndex = fileName.lastIndexOf(".");
		if (beginIndex > 0) {
			String fileExt = fileName.substring(beginIndex);
			newFileName = newFileName + fileExt;
		}
		return newFileName;
	}

	public void convertToAttendList() {
		try{
		//	用java.sql.Blob或byte[]都可以与sql server中的varbinary和image类型映射
		byte[] fileArray = org.springframework.util.FileCopyUtils.copyToByteArray(new File("F:/upload/20120818085242912.jpg"));
		//FileInputStream in = new FileInputStream(photo); 
		//byte[] b = new byte[in.available()]; 
		//in.read(b); 
		//in.close(); 
		//image.setImage(Hibernate.createBlob(b));  或 //Hibernate.createBlob(fin); 
		//attendList.setImage(org.hibernate.Hibernate.createBlob(fileArray));
		attendList.setImage(fileArray);
		}catch(Exception e){
			e.printStackTrace();
		}
		CompApp compApp = new CompApp(compId);
		attendList.setCompApp(compApp);
		User attender = new User(userId);
		attendList.setAttender(attender);
		attendList.setApplyTime(new Date());
		attendList.setLevel("0");
		attendList.setStatue(0);
	}

	public void ConverToSponsor() {
		CompApp compApp = new CompApp(compId);
		sponsor.setCompApp(compApp);
		sponsor.setSponTime(new Date());
		User user = new User(userId);
		sponsor.setSponsor(user);
	}

	public InputStream getInputStream() throws Exception {
		System.out.println("调用getInputStream方法：" + downloadPath);
		return new FileInputStream(downloadPath);
	}

	public int getCompId() {
		return compId;
	}

	public void setCompId(int compId) {

		this.compId = compId;
	}

	public ICompAppService getCompAppService() {
		return compAppService;
	}

	public void setCompAppService(ICompAppService compAppService) {
		this.compAppService = compAppService;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {

		this.userId = userId;
	}

	public CompApp getCompApp() {
		return compApp;
	}

	public void setCompApp(CompApp compApp) {
		this.compApp = compApp;
	}

	public Sponsor getSponsor() {
		return sponsor;
	}

	public void setSponsor(Sponsor sponsor) {
		this.sponsor = sponsor;
	}

	public List<MatchType> getMatchTypeList() {
		return matchTypeList;
	}

	public void setMatchTypeList(List<MatchType> matchTypeList) {
		this.matchTypeList = matchTypeList;
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}

	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public int getCompStatue() {
		return compStatue;
	}

	public void setCompStatue(int compStatue) {
		this.compStatue = compStatue;
	}

	public String getDownloadFileContentType() {
		return downloadFileContentType;
	}

	public void setDownloadFileContentType(String downloadFileContentType) {
		this.downloadFileContentType = downloadFileContentType;
	}

	public String getDownloadFileFileName() {
		return downloadFileFileName;
	}

	public void setDownloadFileFileName(String downloadFile) {
		this.downloadFileFileName = downloadFile;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getDownloadPath() {
		return downloadPath;
	}

	public void setDownloadPath(String downloadPath) {
		this.downloadPath = downloadPath;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getTargetFileName() {
		return targetFileName;
	}

	public void setTargetFileName(String targetFileName) {
		this.targetFileName = targetFileName;
	}

	public IMatchService getMatchService() {
		return matchService;
	}

	public void setMatchService(IMatchService matchService) {
		this.matchService = matchService;
	}

	public AttendList getAttendList() {
		return attendList;
	}

	public void setAttendList(AttendList attendList) {
		this.attendList = attendList;
	}

}
